﻿	 
using System;
using System.Collections.Generic;
using System.Linq;
using RBAC.DAL.Entities;
using NHibernate;
using NHibernate.Criterion;
using RBAC.DAL.Models;


namespace RBAC.DAL.Dal
{
    public class FunctionDAL
    {
        private readonly ISession _session;
        public FunctionDAL(ISession session)
        {
             this._session = session;
        }

        public List<Function> GetAll(FunctionSearch searchCriteria)
        {
            var criteria = _session.CreateCriteria(typeof(Function));

            if (searchCriteria != null)
            {
                #region Search
				//Pk
																	if (!string.IsNullOrEmpty(searchCriteria.FuncName)) 
							{
								if (searchCriteria.EqPk.GetValueOrDefault())
									{
										criteria.Add(Restrictions.Eq("FuncName", searchCriteria.FuncName)); 
									}
								else
									{
										criteria.Add(Restrictions.Like("FuncName", searchCriteria.FuncName, MatchMode.Anywhere));
									}
							}
									  			  //lookup to parent
			  			  if (null != searchCriteria.Domain)
                {
                    criteria.Add(Restrictions.Eq("Domain", searchCriteria.Domain));
                }
			  		  
			 #endregion
					
					#region Sort
					if (searchCriteria.IsSort)
						criteria.AddOrder(searchCriteria.Order);
                    #endregion            
            }			
            return criteria.List<Function>().ToList();
        }


        public void Add(Function function)
        {
			          _session.Save( function);
        }

        public void Update(Function function)
        {
			
				 // chlidren

            var obj = _session.Get<Function>(function.Id);
            if (obj == null)
                throw new Exception("Update Not Success");
			            
            _session.Merge(function);			
           
        }

        public void Delete(List<string> idList)
        {
            int row = _session.CreateQuery("DELETE RBAC.DAL.Entities.Function where Id in (:IdList)").SetParameterList("IdList", idList).ExecuteUpdate();
            if (row != idList.Count)
                throw new Exception("Delete Not Success");
        }
    }
}

